package org.learnaholic.ui.itemtable;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class LabelsTableModel
{
	private final Set<String>					allItems;
	private final Set<String>					selectedItems;
	private final Set<LabelsTableModelListener>	listeners	= new HashSet<LabelsTableModelListener>();

	public LabelsTableModel()
	{
		this.allItems = new HashSet<String>();
		this.selectedItems = new HashSet<String>();
	}

	public void add(String item)
	{
		allItems.add(item);
	}

	public void addAll(Set<String> items)
	{
		allItems.addAll(items);
	}

	public Set<String> getSelected()
	{
		return selectedItems;
	}

	public void addListener(LabelsTableModelListener listener)
	{
		listeners.add(listener);
	}

	public void removeListener(LabelsTableModelListener listener)
	{
		listeners.remove(listener);
	}

	private void notifyListeners(LabelsTableModelEvent evt)
	{
		synchronized (listeners)
		{
			for (Iterator<LabelsTableModelListener> iterator = listeners.iterator(); iterator.hasNext();)
			{
				LabelsTableModelListener listener = iterator.next();
				listener.modelChanged(evt);
			}
		}
	}

	public void setAllSelected(boolean selected)
	{
		HashSet<String> newlySelectedItems = new HashSet<String>();
		HashSet<String> newlyUnselectedItems = new HashSet<String>();

		if (selected)
		{
			selectedItems.addAll(allItems);
			newlySelectedItems.addAll(allItems);
		}
		else
		{
			newlyUnselectedItems.addAll(selectedItems);
			selectedItems.clear();
		}
		notifyListeners(new LabelsTableModelEvent(this, newlySelectedItems, newlyUnselectedItems));
	}

	/**
	 * @param text
	 * @param selected
	 */
	public void setSelected(String item, boolean selected)
	{
		HashSet<String> newlySelectedItems = new HashSet<String>();
		HashSet<String> newlyUnselectedItems = new HashSet<String>();

		if (selected)
		{
			selectedItems.add(item);
			newlySelectedItems.add(item);
		}
		else
		{
			selectedItems.remove(item);
			newlyUnselectedItems.add(item);
		}
		notifyListeners(new LabelsTableModelEvent(this, newlySelectedItems, newlyUnselectedItems));
	}
}
